package keeto.com.vn.classified.utils;

import java.util.LinkedList;

/**
 * @category Log class, it just record the operation step, u can set the max
 *           size of log queue with setMax method, please calls removeTrack
 *           method when u do not use again or exception is happened,u can set setDEBUG to stop this track
 * */
public class OperationRecord {

	private static LinkedList<String> info = new LinkedList<String>();
	private static final Object LOCK = new Object();
	private static int max = 100;
	private static int step = 0;
	private static boolean DEBUG = true;

	public static void setDEBUG(boolean dEBUG) {
		DEBUG = dEBUG;
		if(!DEBUG)
		removeTrack();
	}

	/**
	 * @category Set the log length,default size is 100
	 * */
	public static void setMax(int _max) {
		synchronized (LOCK) {
			max = _max;
		}
	}

	private static void recordTrack(String track) {
		if (max <= info.size()) {
			info.poll();
		}
		step++;
		info.add(track + " ;Step: " + step);
	}

	/**
	 * @category Record the debug information witch includes package's name,
	 *           class's name,method name, line number, time, operation step
	 * */
	public static void record() {
		if(!DEBUG){
			return;
		}
		synchronized (LOCK) {
			recordTrack(getTraceInfo());
		}

	}

	/**
	 * @category Get operation debug
	 * */
	public static LinkedList<String> getRecord() {
		return info;
	}

	public static void removeTrack() {

		synchronized (LOCK) {
			if (null != info) {
				info.clear();
				step = 0;
			}
		}
	}

	private static final int TRACK_INDEX = 4;

	private static String getTraceInfo() {
		StringBuffer sb = new StringBuffer();

		// StackTraceElement[] stacks = new Throwable().getStackTrace();
		// int stacksLen = stacks.length;
		// sb.append("class: ").append(stacks[1].getClassName())
		// .append("; method: ").append(stacks[1].getMethodName())
		// .append("; number: ").append(stacks[1].getLineNumber());
		// StackTraceElement[] e = Thread.currentThread().getStackTrace();
		// System.out.println("方法名       "
		// + Thread.currentThread().getStackTrace()[TRACK_INDEX]
		// .getMethodName());
		// System.out.println("类名    "
		// + Thread.currentThread().getStackTrace()[TRACK_INDEX]
		// .getClassName());
		// System.out.println("文件名   "
		// + Thread.currentThread().getStackTrace()[TRACK_INDEX]
		// .getFileName());
		// System.out.println("所在的行数 "
		// + Thread.currentThread().getStackTrace()[TRACK_INDEX]
		// .getLineNumber());
		sb.append("class: ")
				.append(Thread.currentThread().getStackTrace()[TRACK_INDEX]
						.getClassName())
				.append("; method: ")
				.append(Thread.currentThread().getStackTrace()[TRACK_INDEX]
						.getMethodName())
				.append("; Line number: ")
				.append(Thread.currentThread().getStackTrace()[TRACK_INDEX]
						.getLineNumber()).append("; Time: ")
				.append(System.currentTimeMillis());
		return sb.toString();
	}
}
